//
//  UIColor+CustomColor.m
//  FinanceProject
//
//  Created by 陈显摆 on 2025/1/15.
//

#import "UIColor+CustomColor.h"

@implementation UIColor (CustomColor)


/*! 从HEX字符串得到一个UIColor对象 */
+ (UIColor *)hexColor:(NSString *)hexString
{
    // 获取目标字符串，替换字符并转换成大写字符串
    NSString *colorString = [[hexString stringByReplacingOccurrencesOfString:@"#"
                                                                  withString:@""] uppercaseString];
    CGFloat alpha, red, blue, green;
    switch([colorString length])
    {
        case 3: // #RGB
            alpha = 1.0f;
            red   = [self colorComponentFrom:colorString
                                       start:0
                                      length:1];
            green = [self colorComponentFrom:colorString
                                       start:1
                                      length:1];
            blue  = [self colorComponentFrom:colorString
                                       start:2
                                      length:1];
            break;
        case 4: // #ARGB
            alpha = [self colorComponentFrom:colorString
                                       start:0
                                      length:1];
            red   = [self colorComponentFrom:colorString
                                       start:1
                                      length:1];
            green = [self colorComponentFrom:colorString
                                       start:2
                                      length:1];
            blue  = [self colorComponentFrom:colorString
                                       start:3
                                      length:1];
            break;
        case 6: // #RRGGBB
            alpha = 1.0f;
            red   = [self colorComponentFrom:colorString
                                       start:0
                                      length:2];
            green = [self colorComponentFrom:colorString
                                       start:2
                                      length:2];
            blue  = [self colorComponentFrom:colorString
                                       start:4
                                      length:2];
            break;
        case 8: // #AARRGGBB
            alpha = [self colorComponentFrom:colorString
                                       start:0
                                      length:2];
            red   = [self colorComponentFrom:colorString
                                       start:2
                                      length:2];
            green = [self colorComponentFrom:colorString
                                       start:4
                                      length:2];
            blue  = [self colorComponentFrom:colorString
                                       start:6
                                      length:2];
            break;
        default: // 抛出异常
            [NSException raise:@"无效的颜色值"
                        format:@"颜色值%@是无效的. 正确的格式是#RBG、#ARGB、#RRGGBB或#AARRGGBB", hexString];
            break;
    }
    return [UIColor colorWithRed:red
                           green:green
                            blue:blue
                           alpha:alpha];
}

/*!
 *  获取字符，转换数据类型，改变部分字体颜色
 *
 *  @param string string
 *  @param start  开始位置
 *  @param length 截取长度
 *
 *  @return float
 */
+ (CGFloat)colorComponentFrom:(NSString *)string
                        start:(NSUInteger)start
                       length:(NSUInteger)length
{
    // 截取字符
    NSString *substring = [string substringWithRange:NSMakeRange(start, length)];
    NSString *doubleSubstring = [NSString stringWithFormat:@"%@%@", substring, substring];
    NSString *fullHex = (length == 2 ? substring : doubleSubstring);
    unsigned hexComponent;
    // 字符转成hex，可选前缀为“0x”或“ 0X ”
    [[NSScanner scannerWithString:fullHex] scanHexInt:&hexComponent];
    
    return hexComponent / 255.0;
}

/*  从HEX数值得到一个UIColor对象 */
+ (id)colorWithHex:(unsigned int)hex
{
    return [UIColor colorWithHex:hex
                           alpha:1.0];
}

/*  从HEX数值和Alpha数值得到一个UIColor对象 */
+ (id)colorWithHex:(unsigned int)hex
             alpha:(float)alpha
{
    return [UIColor colorWithRed:((float)((hex & 0xFF0000) >> 16)) / 255.0
                           green:((float)((hex & 0xFF00) >> 8)) / 255.0
                            blue:((float)(hex & 0xFF)) / 255.0
                           alpha:alpha];
}

/* 创建一个随机UIColor对象 */
+ (UIColor *)randomColor
{
    int r = arc4random() % 255;
    int g = arc4random() % 255;
    int b = arc4random() % 255;
    
    return [UIColor colorWithRed:r/255.0
                           green:g/255.0
                            blue:b/255.0
                           alpha:1.0];
}

/*  从已知UIColor对象和Alpha对象得到一个UIColor对象 */
+ (UIColor *)colorWithColor:(UIColor *)color
                      alpha:(float)alpha
{
    if([color isEqual:[UIColor whiteColor]])
        return [UIColor colorWithWhite:1.000
                                 alpha:alpha];
    if([color isEqual:[UIColor blackColor]])
        return [UIColor colorWithWhite:0.000
                                 alpha:alpha];
    
    // 使用CGColorGetComponents方法，获取'color'关联的颜色组件
    const CGFloat *components = CGColorGetComponents(color.CGColor);
    return [UIColor colorWithRed:components[0]
                           green:components[1]
                            blue:components[2]
                           alpha:alpha];
}

+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha
{
    //删除字符串中的空格
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
    {
        return [UIColor clearColor];
    }
    // strip 0X if it appears
    //如果是0x开头的，那么截取字符串，字符串从索引为2的位置开始，一直到末尾
    if ([cString hasPrefix:@"0X"])
    {
        cString = [cString substringFromIndex:2];
    }
    //如果是#开头的，那么截取字符串，字符串从索引为1的位置开始，一直到末尾
    if ([cString hasPrefix:@"#"])
    {
        cString = [cString substringFromIndex:1];
    }
    if ([cString length] != 6)
    {
        return [UIColor clearColor];
    }
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    //r
    NSString *rString = [cString substringWithRange:range];
    //g
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    //b
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:alpha];
}

/*!
 *  UIColor 转UIImage
 *
 *  @param color color
 *
 *  @return UIColor 转UIImage
 */
+ (UIImage *)imageWithColor:(UIColor *)color
{
    CGRect rect=CGRectMake(0,0, 1, 1);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}



//绘制渐变色颜色的方法
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr {

//    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;

    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString1:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString1:toHexColorStr].CGColor];

    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0.f, 0.f);
    gradientLayer.endPoint = CGPointMake(1.f, 0.f);
    
    
//    CGPoint startPoint = CGPointMake(0.0, 0.0);
//    CGPoint endPoint = CGPointZero;
//    endPoint = CGPointMake(1, 0);
//    gradientLayer.startPoint = startPoint;
//    gradientLayer.endPoint = endPoint;

    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];

    return gradientLayer;
}



//绘制渐变色颜色的方法 从上到下渐变
+ (CAGradientLayer *)setGradualTopBottomChangingColor:(UIView *)view fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr {

//    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = view.bounds;

    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString1:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString1:toHexColorStr].CGColor];

    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0.f, 0.f);
    gradientLayer.endPoint = CGPointMake(0.f, 1.f);
    
    
//    CGPoint startPoint = CGPointMake(0.0, 0.0);
//    CGPoint endPoint = CGPointZero;
//    endPoint = CGPointMake(1, 0);
//    gradientLayer.startPoint = startPoint;
//    gradientLayer.endPoint = endPoint;

    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];

    return gradientLayer;
}



//绘制渐变色颜色的方法 如果frame有误 就用这个替换
+ (CAGradientLayer *)setGradualChangingColor:(UIView *)view frame:(CGRect)frame fromColor:(NSString *)fromHexColorStr toColor:(NSString *)toHexColorStr {

//    CAGradientLayer类对其绘制渐变背景颜色、填充层的形状(包括圆角)
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = frame;

    //  创建渐变色数组，需要转换为CGColor颜色
    gradientLayer.colors = @[(__bridge id)[UIColor colorWithHexString1:fromHexColorStr].CGColor,(__bridge id)[UIColor colorWithHexString1:toHexColorStr].CGColor];

    //  设置渐变颜色方向，左上点为(0,0), 右下点为(1,1)
    gradientLayer.startPoint = CGPointMake(0.f, 0.f);
    gradientLayer.endPoint = CGPointMake(1.f, 0.f);
    
    
//    CGPoint startPoint = CGPointMake(0.0, 0.0);
//    CGPoint endPoint = CGPointZero;
//    endPoint = CGPointMake(1, 0);
//    gradientLayer.startPoint = startPoint;
//    gradientLayer.endPoint = endPoint;

    //  设置颜色变化点，取值范围 0.0~1.0
    gradientLayer.locations = @[@0,@1];

    return gradientLayer;
}

//渐变色转image
+ (UIImage *)setGradientWithColors:(NSArray *)colors rect:(CGRect)rect {
    
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    
    gradientLayer.frame = rect;
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(1, 0);
    NSMutableArray *mutColors = [NSMutableArray arrayWithCapacity:colors.count];
    for (UIColor *color in colors) {
        [mutColors addObject:(__bridge id)color.CGColor];
    }
    gradientLayer.colors = [NSArray arrayWithArray:mutColors];
    
    UIGraphicsBeginImageContextWithOptions(gradientLayer.frame.size, gradientLayer.opaque, 0);
    [gradientLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return outputImage;
}



//获取16进制颜色的方法
+ (UIColor *)colorWithHexString1:(NSString *)hexColor {
    hexColor = [hexColor stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if ([hexColor length] < 6) {
        return nil;
    }
    if ([hexColor hasPrefix:@"#"]) {
        hexColor = [hexColor substringFromIndex:1];
    }
    NSRange range;
    range.length = 2;
    range.location = 0;
    NSString *rs = [hexColor substringWithRange:range];
    range.location = 2;
    NSString *gs = [hexColor substringWithRange:range];
    range.location = 4;
    NSString *bs = [hexColor substringWithRange:range];
    unsigned int r, g, b, a;
    [[NSScanner scannerWithString:rs] scanHexInt:&r];
    [[NSScanner scannerWithString:gs] scanHexInt:&g];
    [[NSScanner scannerWithString:bs] scanHexInt:&b];
    if ([hexColor length] == 8) {
        range.location = 4;
        NSString *as = [hexColor substringWithRange:range];
        [[NSScanner scannerWithString:as] scanHexInt:&a];
    } else {
        a = 255;
    }
    return [UIColor colorWithRed:((float)r / 255.0f) green:((float)g / 255.0f) blue:((float)b / 255.0f) alpha:((float)a / 255.0f)];
}



+ (CAGradientLayer *)applyGradientWithColor1:(UIColor *)color1 color2:(UIColor *)color2 frame:(CGRect)frame direction:(GradientApiDirection)direction {
    // 创建渐变层
    CAGradientLayer *gradientLayer = [CAGradientLayer layer];
    gradientLayer.frame = frame;
    
    // 设置渐变的颜色
    gradientLayer.colors = @[(id)color1.CGColor, (id)color2.CGColor];
    
    // 根据传入的方向设置渐变的起始点和结束点
    if (direction == GradientApiDirectionLeftToRight) {
        gradientLayer.startPoint = CGPointMake(0.0, 0.5);  // 从左到右
        gradientLayer.endPoint = CGPointMake(1.0, 0.5);
    } else if (direction == GradientApiDirectionTopToBotton) {
        gradientLayer.startPoint = CGPointMake(0.5, 0.0);  // 从上到下
        gradientLayer.endPoint = CGPointMake(0.5, 1.0);
    }
    
    // 将渐变层添加到当前视图的图层上
//    [view.layer insertSublayer:gradientLayer atIndex:0];
    
    return gradientLayer;
}


@end
